package com.huike.web.controller.common;

import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;

import com.huike.common.utils.file.AliOssUtil;

import com.huike.common.utils.file.FileUtils;
import com.huike.common.utils.uuid.UUID;
import com.sun.xml.bind.v2.TODO;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;


/**
 * ZhouYang
 *
 * @Description 通用请求处理
 * @Date 2023-10-10
 */
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/common")
public class CommonController extends BaseController {

    private final AliOssUtil aliOssUtil;

    private final HttpServletResponse httpServletResponse;

    /**
     * 文件上传接口
     *
     * @param file
     * @return
     */
    @ApiOperation("文件上传接口")
    @PostMapping("/upload")
    public AjaxResult<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀   dfdfdf.pdf
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            // 文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return AjaxResult.success(filePath);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
            return AjaxResult.error("文件上传失败！");
        }
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName) throws Exception {
        String decodedFileName = URLDecoder.decode(fileName, "UTF-8");
        String newFileName = "D:\\img\\download\\" + decodedFileName;
        httpServletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(httpServletResponse, newFileName);
        FileUtils.writeBytes(newFileName, httpServletResponse.getOutputStream());
    }
}

